<?php

namespace app\modules\Product\controllers;

use Yii;
use app\modules\Product\models\ProductRoom;
use app\modules\Product\models\ProductRoomSearch;
use app\modules\Product\models\ProductRoomPrice;
use app\modules\Product\models\Product;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * ProductRoomController implements the CRUD actions for ProductRoom model.
 */
class ProductRoomController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					[
						'allow' => true,
						//'actions' => ['list', 'index','create','view','update','delete'],
						'roles' => ['@'],
					],
				],
			],
		];
	}


    /**
     * Lists all ProductRoom models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProductRoomSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ProductRoom model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProductRoom model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($product_id, $cate=1){//{{{
        $product = Product::findOne($product_id);
		
		$stock = 0;
		$stock = empty($stock) ? $product->stock : $stock;

        if($stock == 2){ // 海外行程
            return $this->render('list2', ['models'=>json_decode($product->rooms, true), 'product' => $product] );
        }

        // 判断是否为该线路添加过价格表                             ->orderby('num desc')
        $ret = ProductRoom::find()->where(['product_id'=>$product_id])->all();

        if(empty($ret)){
            foreach($product->allRoom as $m){

                $range = range($m->min, $m->num);

                foreach($range as $val){
                	$model = new ProductRoom();

                	$model->product_id = $product_id;
                	$model->room_id = $m->id;
                	$model->show= 1;
                    $model->people = $val;

                	$model->save();
                }
            }
            
            $models = ProductRoom::find()->where(['product_id'=>$product_id])->all();
			// 添加操作记录
			$desc = "配置舱房价格";
			Yii::$app->logs->info($product->id, 1, $desc, '' , 2);

        }else{
            $models = $ret; 
        }

        return $this->render('list', [
            'models' => $models,
            'product' => $product,
            'cate' => $cate,
        ]);
    }//}}}

    //添加舱房库存 -- 标准舱房库存格式
    public function actionCreateRoom($product_id){
        $this->layout = '//empty';
        if(empty($product_id)){
            return false;
        }

        $product = Product::findOne($product_id);

        $model = new ProductRoom();
        $model->product_id = $product_id;

        if ($model->load(Yii::$app->request->post())) {
            $model->show = 1;
            if($model->save()){
                return $this->redirect(Yii::$app->request->getReferrer());
            }
        }
        $all_room = $product->allRoom;
        $room = [];
        if($all_room){
            foreach($all_room as $m){
                $room[$m->id] = $m->name.'-'.$m->code;
            }
        }
        return $this->render('create-room', [
            'product' => $product,
            'model' => $model,
            'room' => $room,
        ]);
    }

    /**
     * Updates an existing ProductRoom model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ProductRoom model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ProductRoom model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ProductRoom the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProductRoom::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 保存价格信息
     *
     */
    public function actionSave(){//{{{
        $params = Yii::$app->request->post();            
		
        $data = $data2 =[];
        foreach($params['ProductRoom']['id'] as $key=>$val){
            $data[$key]['id']    =  $val;
            $data[$key]['num']   =  $params['ProductRoom']['num'][$key];
            $data[$key]['price'] =  isset($params['ProductRoom']['price'][$key]) ? $params['ProductRoom']['price'][$key] : '';
            $data[$key]['inside_price'] =  isset($params['ProductRoom']['inside_price'][$key]) ? $params['ProductRoom']['inside_price'][$key] : '';
            $data[$key]['commiss_price'] =  isset($params['ProductRoom']['commiss_price'][$key]) ? $params['ProductRoom']['commiss_price'][$key] : '';
            $data[$key]['show'] =  isset($params['ProductRoom']['show'][$key]) ? 1 : 0;
            //$data[$key]['sort']  = $params['ProductRoom']['sort'][$key];
        }

        foreach($data as $value){
            $model = ProductRoom::findOne($value['id']);
			// 记录操作日志
			if($model->num != $value['num']){ // 库存变更
				$desc = sprintf("%s%s %s 人间 - 库存变更  %s >> %s",$model->room->name,$model->room->code , $model->people, $model->num, $value['num']);
				Yii::$app->logs->info($model->product_id, 1, $desc, '' , 2);
			}

			if($model->price != $value['price']){ // 直客价
				$desc = sprintf("%s%s %s 人间 - 直客价变更  %s >> %s",$model->room->name,$model->room->code , $model->people, $model->price, $value['price']);
				Yii::$app->logs->info($model->product_id, 1, $desc, '' , 2);
			}

			if($model->price != $value['price']){ // 同业价
				$desc = sprintf("%s%s %s 人间 - 同业价变更  %s >> %s",$model->room->name,$model->room->code , $model->people, $model->inside_price, $value['inside_price']);
				Yii::$app->logs->info($model->product_id, 1, $desc, '' , 2);
			}


            $model->num = $value['num'];
            $model->price = $value['price'];
            $model->inside_price = $value['inside_price'];
            $model->commiss_price = $value['commiss_price'];
            $model->show = $value['show'];
            //$model->sort = $value['sort'];

            $ret = $model->save();
        }

        $product_id = $params['ProductRoom']['product_id'];
        // 舱房价格备注
        $room_remark = isset($params['Product']['room_remark']) ? $params['Product']['room_remark'] : '';
        if($room_remark){
            $product = Product::findOne($product_id);
            $product->room_remark = $room_remark;
            $product->save();
        }

        return $this->redirect([sprintf('/product/product-room/create?product_id=%d', $product_id)]);
    }//}}}

    // 海外航线舱房信息保存
    public function actionSave2(){//{{{

        $params = Yii::$app->request->post();
            
        foreach($params['ProductRoom'] as $key=>$val){ 
           $params['ProductRoom'][$key]['sell_out'] =  isset($params['ProductRoom'][$key]['sell_out']) ? 1 : 0;
        }
            
        $product = Product::findOne($params['product_id']);
		
        if(isset($params['ProductRoom']) && !empty($params['ProductRoom']) ){
            $product->rooms = json_encode($params['ProductRoom']);
        }

        // 舱房价格备注
        $room_remark = $params['Product']['room_remark'];
        if($room_remark){
            $product->room_remark = $room_remark;
        }
        $product->save();

        return $this->redirect([sprintf('/product/product-room/create?product_id=%d', $product->id)]);
    }//}}}

	/**
	 * 检查舱房是否在订单中使用过
	 *
	 */
	public function actionIsOrderUse($id){//{{{

        $model = $this->findModel($id);

		if(empty($model->stockNum)){ //  未使用

			print_r('true');	
		}else{
		
			print_r('false');	
		}
	}//}}}


    public function actionSellOut($id,$checked){

        $model = $this->findModel($id);
        if($checked == 'true'){
            $model->sell_out = 1;
        }else{
            $model->sell_out = 0;
        }
        if($model->save()){
            echo 1; 
        }else{
            echo 0; 
        }
        
    }
	/**
	 * 检查舱房是否足够 标准舱房格式
	 */
	public function actionCheckSell($id, $num){
		
        $model = $this->findModel($id);
	
		if($model->stockNum <= $num){
			echo 'true';
		}else{
			//echo 'false';
			echo $model->stockNum;
		}
	}

	/**
	 * 检查舱房是否足够 自定义舱房格式
	 */
	public function actionCheckSell2($product_id, $id, $num){
		
		$product = Product::findOne($product_id);

		if($product && $id){
			
			$n = $product->getSellStockRoom($id);
	
			if($n <= $num){
				echo 'true';
			}else{
				//echo 'false';
				echo $n;
			}
		}
	}



}
